package com.ldzy.controller;

import com.ldzy.exception.UserException;
import com.ldzy.pojo.User;
import com.ldzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String toHome(){
        System.out.println(1111);
        return "main";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin/login.jsp";
    }

    @PostMapping("/login")
    public String login(User user, Model model, HttpSession session){
        try {
            User user1 = userService.login(user);
            session.setAttribute("user",user1);
        }catch (UserException e){
            e.printStackTrace();
            model.addAttribute("msg",e.getResultCode().getDesc());
            return "forward:/admin/login.jsp";
        }
        return "redirect:/admin/main.jsp";
    }
}
